package com.project.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * 切面类
 */
@Component  //声明该类为spring组件类
@Aspect //声明该类为一个切面类
public class ServiceAspect {
    //execution（）表示前置通知应用的范围
    @Before("execution(* com.project.service..*.*(..))")
    public void beforeMethod(){
        System.out.println("前通知");
    }

//    @AfterReturning("execution(* com.project.service..*.*(..))")
//    @AfterReturning 目标方法正确执行才执行。
//    @After 不管目标方法是否抛出异常都执行
    @After("execution(* com.project.service..*.*(..))")
    public void afterMethod(){
        System.out.println("后置通知");
    }

    @Around("execution(* com.project.service..*.*(..))")
    public Object aroundMerhod(ProceedingJoinPoint joinPoint){
        try {
            System.out.println("环绕前");
            //执行目标方法，得到方法执行后的返回值
            Object retrunObj = joinPoint.proceed();
            //返回目标对象
//            Object targetObj = joinPoint.getTarget();
            System.out.println("环绕后");
            return retrunObj;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }

    //value = "通知应用范围" e:异常变量  joinPoint：连接点
//    @AfterThrowing(value = "execution(* com.project.service..*.*(..))", throwing = "e")
//    public void throwException(JoinPoint joinPoint,Exception e){
//       //得到目标对象
//        Object targetObj = joinPoint.getTarget();
//        //得到目标方法的名称
//        String methodName = joinPoint.getSignature().getName();
//        System.out.println("执行"+targetObj.getClass().getName()+"类的"
//        +methodName+"()方法，抛出"+e.getClass().getName()+"异常");
//    }


    @AfterThrowing(value = "execution(* com.project.service..*.*(..))",throwing = "e")
    public void throwException(JoinPoint jp,Exception e){
        //得到目标对象
        Object targetObj = jp.getTarget();
        //得到目标方法名
        String metnodName = jp.getSignature().getName();
        System.out.println("执行"+targetObj.getClass().getName() +"的"+metnodName+"()方法，抛出"+e.getClass().getName());
    }

}
